<?php

namespace app\achievement\controller;

use app\common\model\Engineers;
use app\common\model\MenuModel;
use app\common\model\OaAchievementWorkersModel;
use app\common\model\OaEngineersPerformanceModel;
use app\common\model\WorkOrderModel;
use app\common\model\CustomerModel;
use app\common\model\OaWorkersModel;
use app\common\model\FollowModel;
use app\common\model\Operation;
use app\common\model\Administrative;
use app\common\model\ChannelModel;
use app\common\model\ChannelPromotersModel;
use app\common\model\WithdrawModel;
use think\Db;

/**
 *    总后台首页  控制器
 * Class Index
 * @package app\achievement\controller
 */
class Index extends Base
{

    protected $customer_model;
    protected $work_order_model;
    protected $oa_workers_model;
    protected $follow_model;
    protected $oa_achievement_workers_model;
    protected $oa_engineers_performance_model;
    protected $engineers_model;
    protected $operation;
    protected $administrative;
    protected $channel_model;
    protected $channel_promoters_model;
    protected $withdraw_model;

    // 初始化构造方法，实例化模型
    public function __construct()
    {
        parent::__construct();
        $this->customer_model = new CustomerModel();  // 用户模型
        $this->work_order_model = new WorkOrderModel(); // 工单模型
        $this->oa_workers_model = new OaWorkersModel();
        $this->follow_model = new FollowModel();
        $this->oa_achievement_workers_model = new OaAchievementWorkersModel();  // 职工业绩表模型
        $this->oa_engineers_performance_model = new OaEngineersPerformanceModel();  // 工程人员业绩模型
        $this->engineers_model = new Engineers();  // 工程人员模型
        $this->operation = new Operation();  // 省级承包商模型
        $this->administrative = new Administrative();  // 行政中心模型
        $this->channel_model = new ChannelModel();  // 渠道模型
        $this->channel_promoters_model = new ChannelPromotersModel();  // 渠道推广模型
        $this->withdraw_model = new WithdrawModel();  // 提现模型
    }

    public function index()
    {
        return $this->fetch('/index');
    }

    public function doindex()
    {
        // 获取今日时间戳
        $today_start = strtotime(date('Y-m-d 00:00:00'));
        $today_end = strtotime(date('Y-m-d H:i:s'));
        $between = ['between', [$today_start, $today_end]];

        // 今日结算积分---市场推广、渠道商、推广、省级承包商、区县级承包商————————————————————————
        $where['a.add_time'] = $between;
        $join = [
            ['oa_achievement o', 'o.achievement_id = a.achievement_id', 'LEFT'],
        ];
        $field = 'sum(a.money) money';
        $oa_today_money = $this->oa_achievement_workers_model->getOne($where, $field, $join)['money'] ?? 0;
        unset($where['a.add_time']);
        // 累计结算积分---市场推广
        $oa_total_money = $this->oa_achievement_workers_model->getOne($where, $field, $join)['money'] ?? 0;

        unset($where);
        // 今日结算积分---工程人1员——————————————————————————————————————
        $where['a.add_time'] = $between;
        $join = [
            ['engineers e', 'e.engineers_id = a.engineers_id', 'left'],  // 工程人员表---工程人员业绩表
            ['administrative_info ai', 'ai.a_id=e.administrative_id', 'left']
        ];
        $where['ai.company_id'] = $this->company_id;
        $en_today_money = $this->oa_engineers_performance_model->getOne($where, $field, $join)['money'] ?? 0;
        unset($where['a.add_time']);

        // 累计结算积分---工程人员
        $en_total_money = $this->oa_engineers_performance_model->getOne($where, $field, $join)['money'] ?? 0;

        //合计结算积分————————————————————————————
        $data['today_money'] = formatMoneys($oa_today_money + $en_today_money);
        $data['total_money'] = formatMoneys($oa_total_money + $en_total_money);
        unset($where);

        // 市场推广今日提现——————————————————————————————
        $where['complete_time'] = $between;
        $where['cash_order_state'] = 2;
        $where['play_money_state'] = ['IN', [2, 3]];
        $where['c.user_belong_to_company'] = $this->company_id;
        $where['a.role'] = 6;
        $field = 'sum(cash_order_money) money';
        $join = [
            ['oa_workers ow', 'ow.workers_id=a.uid', 'left'],
            ['customer c', 'c.user_id=ow.user_id', 'left'],
        ];
        //手续费
        //$oa_today_payment_fee = $this->withdraw_model->getOne($where, 'sum(a.payment_fee) today_payment_fee',$join)['today_payment_fee'] ?? 0;
        //今日提现打款
        $oa_today_cash_money = $this->withdraw_model->getOne($where, $field, $join)['money'] ?? 0;
        $oa_today_withdraw_money = formatMoneys($oa_today_cash_money, 2);//今日总的提现积分=提现积分+手续费
        unset($where['complete_time']);
        //市场推广累计提现
        //$oa_total_payment_fee= $this->withdraw_model->getOne($where, 'sum(a.payment_fee) total_payment_fee',$join)['total_payment_fee'] ?? 0;
        $oa_total_cash_money = $this->withdraw_model->getOne($where, $field, $join)['money'] ?? 0;
        $oa_total_withdraw_money = formatMoneys($oa_total_cash_money, 2);

        //渠道商今日提现————————————————————————————
        $where['complete_time'] = $between;
        $where['a.role'] = 4;
        $join = [
            ['customer c', 'c.user_id=a.uid', 'left'],
        ];
        //手续费
        //$ch_today_payment_fee = $this->withdraw_model->getOne($where, 'sum(a.payment_fee) today_payment_fee',$join)['today_payment_fee'] ?? 0;
        //今日提现打款
        $ch_today_cash_money = $this->withdraw_model->getOne($where, $field, $join)['money'] ?? 0;
        $ch_today_withdraw_money = formatMoneys($ch_today_cash_money, 2);//今日总的提现积分=提现积分+手续费

        unset($where['complete_time']);
        //渠道累计提现
        //$ch_total_payment_fee= $this->withdraw_model->getOne($where, 'sum(a.payment_fee) total_payment_fee',$join)['total_payment_fee'] ?? 0;
        $ch_total_cash_money = $this->withdraw_model->getOne($where, $field, $join)['money'] ?? 0;
        $ch_total_withdraw_money = formatMoneys($ch_total_cash_money, 2);
        unset($where);

        //工程人员今日提现————————————————————————————————————————————————————
        $where['complete_time'] = $between;
        $where['cash_order_state'] = 2;
        $where['play_money_state'] = ['IN', [2, 3]];
        $where['m.company_id'] = $this->company_id;
        $where['a.role'] = 5;
        $join = [
            ['engineers e', 'e.engineers_id=a.uid', 'left'],
            ['administrative_info m', 'm.a_id=e.administrative_id', 'left'],
        ];
        //手续费
        //$en_today_payment_fee = $this->withdraw_model->getOne($where, 'sum(a.payment_fee) today_payment_fee',$join)['today_payment_fee'] ?? 0;
        //今日提现打款
        $en_today_cash_money = $this->withdraw_model->getOne($where, $field, $join)['money'] ?? 0;
        $en_today_withdraw_money = formatMoneys($en_today_cash_money, 2);//今日总的提现积分=提现积分+手续费
        unset($where['complete_time']);
        //工程人员累计提现
        //$en_total_payment_fee= $this->withdraw_model->getOne($where, 'sum(a.payment_fee) total_payment_fee',$join)['total_payment_fee'] ?? 0;
        $en_total_cash_money = $this->withdraw_model->getOne($where, $field, $join)['money'] ?? 0;
        $en_total_withdraw_money = formatMoneys($en_total_cash_money, 2);
        unset($where);

        //省级承包商、区县级承包商今日提现————————————————————————————————————
        $wheres['complete_time'] = $between;
        $wheres['cash_order_state'] = 2;
        $wheres['play_money_state'] = ['IN', [2, 3]];
        $wheres['role'] = ['IN', [1, 2, 3]];
        $field = 'cash_order_money,role,uid';
        $admin_today_list = $this->withdraw_model->getAll($wheres, $field, 1, -1, '', 'uid,role');
        $today_money = 0;
        if (!empty($admin_today_list)) {
            foreach ($admin_today_list as $k => $v) {
                if ($v['role'] == 2) {//省级承包商商
                    $operation = $this->operation->findOperation(['o_id' => $v['uid'], 'company_id' => $this->company_id]);
                    if ($v['uid'] == $operation['o_id']) {
                        $today_money += $v['cash_order_money'] ?? 0;
                    }
                } else if ($v['role'] == 3) {//区县级承包商
                    $operation = $this->operation->findAdministrative(['a_id' => $v['uid'], 'company_id' => $this->company_id]);
                    if ($v['uid'] == $operation['a_id']) {
                        $today_money += $v['cash_order_money'] ?? 0;
                    }

                }

            }
        }
        $admin_today_money = $today_money ? formatMoneys($today_money, 2) : 0;
        unset($wheres['complete_time']);
        //省级承包商、区县级承包商累计提现——————————————————————————————————————————————
        $admin_total_list = $this->withdraw_model->getAll($wheres, $field, 1, -1, '', 'uid,role');
        $total_money = 0;
        if (!empty($admin_total_list)) {
            foreach ($admin_total_list as $k => $v) {
                if ($v['role'] == 2) {//省级承包商商
                    $operation = $this->operation->findOperation(['o_id' => $v['uid'], 'company_id' => $this->company_id]);
                    if ($v['uid'] == $operation['o_id']) {
                        $total_money += $v['cash_order_money'] ?? 0;
                    }
                } else if ($v['role'] == 3) {//区县级承包商
                    $operation = $this->operation->findAdministrative(['a_id' => $v['uid'], 'company_id' => $this->company_id]);
                    if ($v['uid'] == $operation['a_id']) {
                        $total_money += $v['cash_order_money'] ?? 0;
                    }

                }

            }
        }
        $admin_total_money = $total_money ? formatMoneys($total_money, 2) : 0;
        //累计提现————————————————————————————————
        $data['today_cash_money'] = $oa_today_withdraw_money + $ch_today_withdraw_money + $en_today_withdraw_money + $admin_today_money;
        $data['total_cash_money'] = $oa_total_withdraw_money + $ch_total_withdraw_money + $en_total_withdraw_money + $admin_total_money;

        // 今日新增市场推广————————————————————————————————————————————————
        $where['a.add_time'] = $between;
        $where['is_dealer'] = 1;
        $where['account_status'] = 1;
        $where['user_belong_to_company'] = $this->company_id;
        $data['today_add_workers'] = $this->customer_model->getCount($where);
        unset($where['a.add_time']);
        // 累计市场推广数
        $data['total_workers'] = $this->customer_model->getCount($where);
        unset($where);

        // 今日新增工程人员——————————————————————————————————————————————————
        $where['reg_time'] = $between;
        $where['engineers_status'] = 2;
        $where['ai.company_id'] = $this->company_id;
        $join = [
            ['administrative_info ai', 'ai.a_id=e.administrative_id', 'left']
        ];
        $data['today_add_engineers'] = $this->engineers_model->getCount($where, $join);
        unset($where['reg_time']);
        // 累计工程人员数
        $data['total_engineers'] = $this->engineers_model->getCount($where, $join);
        unset($where);

        // 统计近7天走势图-----------------------------------------------------
        $seven = [];
        $data['seven'] = [];
        //近7天日期
        for ($i = 0; $i < 7; $i++) {
            $seven[$i]['start'] = date('Y-m-d 00:00:00', strtotime('+' . $i - 7 . ' days', time()));
            $seven[$i]['end'] = date('Y-m-d 23:59:59', strtotime('+' . $i - 7 . ' days', time()));
            $seven[$i]['time'] = date('m.d', strtotime('+' . $i - 7 . ' days', time()));
            array_push($data['seven'], date('m.d', strtotime('+' . $i - 7 . ' days', time())));
        }

        // 结算积分走势————————————————————————
        foreach ($seven as $k => $v) {
            // 近7天结算积分---市场推广、渠道商、推广、省级承包商、区县级承包商——————————————————————————————
            $where['a.add_time'] = ['between', [strtotime($v['start']), strtotime($v['end'])]];
            $field = 'sum(a.money) money';
            $join = [
                ['oa_achievement o', 'o.achievement_id = a.achievement_id', 'LEFT'],
            ];
            $data['seven_day_money'][$k] = formatMoneys($this->oa_achievement_workers_model->getOne($where, $field, $join)['money']) ?? 0;
            unset($where);
            // 近7天结算积分---工程人员——————————————————————————————————————————————
            $join = [
                ['engineers e', 'e.engineers_id = a.engineers_id', 'left'],  // 工程人员表---工程人员业绩表
                ['administrative_info ai', 'ai.a_id=e.administrative_id', 'left']
            ];
            $where['ai.company_id'] = $this->company_id;
            $where['a.add_time'] = ['between', [strtotime($v['start']), strtotime($v['end'])]];;
            $data['seven_day_money'][$k] += formatMoneys($this->oa_engineers_performance_model->getOne($where, $field, $join)['money']) ?? 0;
            unset($where);
        }


        // 提现打款走势————————————————————————————
        foreach ($seven as $k => $v) {
            $data['seven_day_cash_money'][$k] = 0;
            // 近7天提现打款——市场推广————————————————
            $where['complete_time'] = ['between', [strtotime($v['start']), strtotime($v['end'])]];
            $where['cash_order_state'] = 2;
            $where['play_money_state'] = ['IN', [2, 3]];
            $where['user_belong_to_company'] = $this->company_id;
            $where['a.role'] = 6;
            $field = 'sum(cash_order_money) money';
            $join = [
                ['oa_workers ow', 'ow.workers_id=a.uid', 'left'],
                ['customer c', 'c.user_id=ow.user_id', 'left'],
            ];
            $workers_money = $this->withdraw_model->getOne($where, $field, $join)['money'] ?? 0;
            $data['seven_day_cash_money'][$k] += formatMoneys($workers_money, 2);

            // 近7天提现打款——渠道商、推广员————————————————
            $join = [
                ['customer c', 'c.user_id=a.uid', 'left'],
            ];
            $where['a.role'] = 4;
            $channel_money = $this->withdraw_model->getOne($where, $field, $join)['money'] ?? 0;
            $data['seven_day_cash_money'][$k] += formatMoneys($channel_money, 2);
            unset($where);

            // 近7天提现打款——工程人员————————————————
            $where['complete_time'] = ['between', [strtotime($v['start']), strtotime($v['end'])]];
            $where['cash_order_state'] = 2;
            $where['play_money_state'] = ['IN', [2, 3]];
            $where['a.role'] = 5;
            $where['m.company_id'] = $this->company_id;
            $join = [
                ['engineers e', 'e.engineers_id=a.uid', 'left'],
                ['administrative_info m', 'm.a_id=e.administrative_id', 'left'],
            ];
            $engineers_money = $this->withdraw_model->getOne($where, $field, $join)['money'] ?? 0;
            $data['seven_day_cash_money'][$k] += formatMoneys($engineers_money, 2);
            unset($where);

            // 近7天提现打款——省级承包商————————————————
            $where['complete_time'] = ['between', [strtotime($v['start']), strtotime($v['end'])]];
            $wheres['cash_order_state'] = 2;
            $wheres['play_money_state'] = ['IN', [2, 3]];
            $where['a.role'] = 2;
            $where['o.company_id'] = $this->company_id;
            $join = [
                ['operation_info o', 'o.o_id=a.uid', 'left'],
            ];
            $operation_money = $this->withdraw_model->getOne($where, $field, $join)['money'] ?? 0;
            $data['seven_day_cash_money'][$k] += formatMoneys($operation_money, 2);
            unset($where);

            // 近7天提现打款——区县级承包商————————————————
            $where['complete_time'] = ['between', [strtotime($v['start']), strtotime($v['end'])]];
            $wheres['cash_order_state'] = 2;
            $wheres['play_money_state'] = ['IN', [2, 3]];
            $where['a.role'] = 3;
            $where['o.company_id'] = $this->company_id;
            $join = [
                ['administrative_info o', 'o.a_id=a.uid', 'left'],
            ];
            $administrative_money = $this->withdraw_model->getOne($where, $field, $join)['money'] ?? 0;
            $data['seven_day_cash_money'][$k] += formatMoneys($administrative_money, 2);
            unset($where);
        }

        // 业绩排名市场推广、省级承包商、区县级承包商、渠道商、渠道推广员——————————————————————————————————————
        $join = [
            ['oa_achievement h', 'a.achievement_id = h.achievement_id', 'LEFT'],
        ];
        $achieve_list = $this->oa_achievement_workers_model->getJoinGroupAll([], 'sum(a.money) money,a.workers_id,a.role,a.workers_position', $join, 'a.workers_id,a.role', 1, 15, 'money desc');
        if (!empty($achieve_list)) {
            foreach ($achieve_list as $k => $v) {
                if ($v['role'] == 1) {
                    //市场推广
                    $workers_rank = $this->oa_workers_model->getOne(['workers_id' => $v['workers_id']], 'workers_name');
                    $data['workers_rank'][$k]['workers_name'] = $workers_rank['workers_name'] ?? '';
                    $data['workers_rank'][$k]['money'] = formatMoneys($v['money']) ?? '';
                    ksort($data['workers_rank']);
                } else if ($v['role'] == 2) {
                    //工程人员
                    $engineers_data = $this->engineers_model->getOne(['engineers_id' => $v['workers_id']], 'engineers_name');
                    $data['engineers_rank'][$k]['engineers_name'] =$engineers_data['engineers_name'] ?? '';
                    $data['engineers_rank'][$k]['money'] =formatMoneys($v['money']) ?? '';
                    ksort($data['engineers_rank']);
                } else if ($v['role'] == 3) {
                    if ($v['workers_position'] ==2){
                        //区县承包商
                        $administrative = $this->administrative->findOne(['a_id' => $v['workers_id']], 'company_name');
                        $data['administrative_rank'][$k]['company_name'] = $administrative['company_name'] ?? '';
                        $data['administrative_rank'][$k]['money'] = formatMoneys($v['money']) ?? '';
                        ksort($data['administrative_rank']);
                    }elseif ($v['workers_position'] == 3){
                        //市级承包商
                        $operation = $this->operation->findOne(['o_id' => $v['workers_id']], 'company_name');
                        $data['city_rank'][$k]['company_name'] = $operation['company_name'] ?? '';
                        $data['city_rank'][$k]['money'] = formatMoneys($v['money']) ?? '';
                        ksort($data['city_rank']);
                    }elseif ($v['workers_position'] == 4){
                        //省级承包商
                        $operation = $this->operation->findOne(['o_id' => $v['workers_id']], 'company_name');
                        $data['operation_rank'][$k]['company_name'] = $operation['company_name'] ?? '';
                        $data['operation_rank'][$k]['money'] = formatMoneys($v['money']) ?? '';
                        ksort($data['operation_rank']);
                    }
                } else if ($v['role'] == 4) {
                    //渠道商
                    $channel_rank = $this->channel_model->getOne(['id' => $v['workers_id']], 'name');
                    $data['channel_rank'][$k]['name'] = $channel_rank['name'] ?? '';
                    $data['channel_rank'][$k]['money'] = formatMoneys($v['money']) ?? '';
                    ksort($data['channel_rank']);
                } else {
                    //渠道推广
                    $channel_promoters_rank = $this->channel_promoters_model->getOne(['channel_promoter_id' => $v['workers_id']], 'name');
                    $data['channel_promoters_rank'][$k]['name'] = $channel_promoters_rank['name'] ?? '';
                    $data['channel_promoters_rank'][$k]['money'] = formatMoneys($v['money']) ?? '';
                    ksort($data['channel_promoters_rank']);
                }
            }
        }
        unset($where);
        // 工程业绩排名
        $join = [
            ['engineers e', 'e.engineers_id = a.engineers_id', 'left'],  // 工程人员表---工程人员业绩表
            ['administrative_info ai', 'ai.a_id=e.administrative_id', 'left']
        ];
        $where['ai.company_id'] = $this->company_id;
        $where['engineers_status'] = 2;
        $field = 'sum(a.money) money,a.engineers_id,e.engineers_name';
        $group = 'a.engineers_id';
        $order = 'money DESC';
        $data['engineers_rank'] = $this->oa_engineers_performance_model->getJoinGroupAll($where, $field, $join, $group, 1, 15, $order);
        unset($where);
        // 模板赋值
        $this->assign('data', $data);
        // 调用视图
        return $this->fetch('index');
    }

    /**
     * 查询子菜单栏
     */
    public function MenuList()
    {
        if (request()->isPost()) {
            $meun = new MenuModel();
            $id = input("param.id");
            $data = $meun->getSubmenu($id, $this->set['auth_rule'], session($this->set['db_name'] . 'rule'));
            return json(['code' => 1, 'msg' => '', 'data' => $data]);
        }
    }

}
